package com.oscroll.template.lesson;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public abstract class JDBCTemplate {

    private DataSource dataSource;
    public JDBCTemplate(DataSource dataSource){
        this.dataSource = dataSource;
    }

    private Connection getConnection() throws Exception{
        return this.dataSource.getConnection();
    }

    private PreparedStatement createPreparedStatement(Connection conn,String sql) throws Exception{
        return conn.prepareStatement(sql);
    }

    private ResultSet excuteQuery(PreparedStatement pstmt,Object[] values) throws Exception{
        for(int i=0;i<values.length;i++){
            pstmt.setObject(i,values[i]);
        }
        return pstmt.executeQuery();
    }

    private void closeStatement(Statement stmt) throws Exception{
        stmt.close();
    }
    private void closeResultSet(ResultSet rs) throws Exception{
        rs.close();
    }
    private void closeConnection(Connection conn) throws Exception{
        // 回收conn
    }

    public List<Object> excuteQuery(String sql,Object[] values){
        try {
            // 1、获取连接
            Connection conn = this.getConnection();

            // 2、创建语句集
            PreparedStatement pstmt = this.createPreparedStatement(conn,sql);

            // 3、执行语句集，获得结果集
            ResultSet rs = pstmt.executeQuery();

            // 4、解析语句集
            List<Object> result = new ArrayList<Object>();
            int rowNum = 1;
            while(rs.next()){
                result.add(processResult(rs,rowNum++));
            }

            // 5、关闭结果集
            rs.close();

            // 6、关闭语句集
            pstmt.close();

            // 7、关闭连接
            conn.close();

        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public abstract Object processResult(ResultSet rs,int rowNum) throws Exception;

}
